package com.googlecode.studentrecords;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileIO {
	
	/**Indicates if an error occurred*/
	boolean error = false;
	
	/**Reads external file containing student info
	 * 
	 * @param path			Name of text file containing student info
	 * @return				String array containing a copy of the student's info
	 */
	public String[] readFile(String path)
	{
		/**Temporary student array*/
		String[] student = new String[5];
		
		
		try
		{
			FileReader reader = new FileReader(path);
			BufferedReader br = new BufferedReader(reader);
			
			for(int i = 0; i < 5; i ++)
			{
				student[i] = br.readLine();
			}
			br.close();
			
		}
		catch(FileNotFoundException e)
		{
			error = true;
			//e.printStackTrace();
			
		} 
		catch (IOException e) 
		{
			error = true;
			//e.printStackTrace();
		}
		finally
		{
			if(error)
				System.out.println("An error occurred when attempting to access the student files.");
		}
		
		return student;
	}
	
	/**Replaces selected line in selected file with newText
	 * 
	 * @param path				Selected file
	 * @param oldText			Text to be replaced
	 * @param newText			Text to be replaced with
	 */
	public void editFile(String path, String oldLine, String newLine)
	{
		try
        {
        FileReader reader = new FileReader(path);
        BufferedReader br = new BufferedReader(reader);
        String line = ""; 
        String oldText = "";
        while((line = br.readLine()) != null)
            {
            oldText += line + "\r\n";
        }
        reader.close();

        String newtext = oldText.replaceAll(oldLine, newLine);
       
        FileWriter writer = new FileWriter(path);
        writer.write(newtext);
        writer.close();
    }
    catch (IOException e)
        {
    		e.printStackTrace();
        }	
		
	}

}
